package top.ahzy.seobench.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.ahzy.seobench.config.JWTConfig;
import top.ahzy.seobench.exception.NotLoginException;
import top.ahzy.seobench.model.entity.User;
import top.ahzy.seobench.result.ResultCodeEnums;
import top.ahzy.seobench.util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class FilterInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Object token =  request.getHeader(JWTConfig.tokenHeader);
        if (token == null) {
            throw new NotLoginException("token不存在", ResultCodeEnums.LOGIC_EXPIRE.getCode());
        }


        User user = JwtUtil.parseAccessToken(token.toString());
        if (user == null) {
            throw new NotLoginException("token过期", ResultCodeEnums.LOGIC_EXPIRE.getCode());
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//        System.out.println("postHandle: " + request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("afterCompletion: " + request.getRequestURI());
    }

}
